package com.power.sifa.approve.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollectionUtil;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.utils.ExcelUtil;
import com.plf.common.utils.SpringHolder;
import com.plf.common.utils.StringUtil;
import com.plf.core.common.file.FileController;
import com.power.sifa.approve.api.IApl_agentFeign;
import com.power.sifa.approve.model.Apl_agent;
import com.power.sifa.approve.model.pageInfo.Apl_agentPageInfo;
import com.power.sifa.approve.service.Apl_agentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 委托代理人控制器
 */

//@Slf4j
//@PowerLog
@RestController
@Api(value = "Apl_agentController", tags = {"委托代理人"})
public class Apl_agentController implements IApl_agentFeign {

    @Resource
    private Apl_agentService apl_agentService;


    @Override
    @ApiOperation("查询委托代理人分页列表")
    @SaCheckPermission("apl_agent_list")
    public ResponseDTO list(Apl_agentPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        Page<Apl_agent> page = this.apl_agentService.findAll(pageInfo);
        List list = new ArrayList();
        if (!page.isEmpty()) {
            for (Apl_agent apl_agent : page) {
                apl_agent.geneText();
                list.add(apl_agent);
            }
        }
        PageDataResponse p = new PageDataResponse(list, page.getTotalElements(), page.getSize(), pageInfo.getPageNumber() <= 1 ? 1 : pageInfo.getPageNumber());
        return ResponseDTO.succData(p);
    }

    @Override
    @ApiOperation("查看委托代理人")
    @SaCheckPermission("apl_agent_view")
    public ResponseDTO view(String id) {
        Assert.notNull(id, "id不能为空");
        Apl_agent apl_agent = apl_agentService.getById(id);
        if (apl_agent != null) {
            apl_agent.geneText();
        }
        return ResponseDTO.succData(apl_agent);
    }

    @Override
    @ApiOperation("删除委托代理人")
    @SaCheckPermission("apl_agent_del")
    public ResponseDTO delete(String id) {
        Assert.notNull(id, "id不能为空");
        apl_agentService.removeById(id);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation("保存或修改委托代理人")
    @SaCheckPermission("apl_agent_save")
    public ResponseDTO save(Apl_agent apl_agent) {
        Assert.notNull(apl_agent, "apl_agent不能为空");
        apl_agentService.saveOrUpdate(apl_agent);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation(value = "批量删除委托代理人")
    @SaCheckPermission("apl_agent_del")
    public ResponseDTO batchDel(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "ids不能为空");
        List<Integer> list = Arrays.asList(ids.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        apl_agentService.removeByIds(list);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation(value = "导出excel")
    @SaCheckPermission("apl_agent_list")
    public void output(HttpServletResponse response, Apl_agentPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo不能为空");
        String title = "委托代理人";
        String[] heads = {"applyid+nanoid", "代理人类型", "姓名", "证件类型", "证件号", "性别", "民族", "送达地址（住址）", "工作单位（律所名称）", "电话", "邮政编码", "applyid", "排序", "代理申请人"};
        String[] fields = {"id", "type", "name", "cardtype", "cardno", "gender", "nation", "addr", "unit", "tel", "postcode", "applyid", "sortnum", "applicantname"};
        Page<Apl_agent> page = this.apl_agentService.findAll(pageInfo);
        ExcelUtil.exportXls(title, heads, fields, page.getContent(), response);
    }

    @Override
    @ApiOperation(value = "导出excel模板")
    public void exportExcelTemplate(HttpServletResponse response) {
        String title = "委托代理人";
        //id自增或list从表可自行删除，需与导入项一致
        String[] heads = {"applyid+nanoid", "代理人类型", "姓名", "证件类型", "证件号", "性别", "民族", "送达地址（住址）", "工作单位（律所名称）", "电话", "邮政编码", "applyid", "排序", "代理申请人"};
        ExcelUtil.exportXls(title, heads, null, null, response);
    }

    @Override
    @ApiOperation(value = "导入excel")
    public ResponseDTO importExcel(MultipartFile file) throws IOException {
        Assert.notNull(file, "file不能为空");
        //id自增或list从表可自行删除，需与下载的模板中导入项一致
        String[] fields = {"id", "type", "name", "cardtype", "cardno", "gender", "nation", "addr", "unit", "tel", "postcode", "applyid", "sortnum", "applicantname"};
        List<Apl_agent> list = (List<Apl_agent>) ExcelUtil.Import(fields, file, Apl_agent.class);
        if (!CollectionUtils.isEmpty(list)) {
            this.apl_agentService.saveAll(list);
        }
        return ResponseDTO.succ();
    }

    @Override
    public ResponseDTO getAgentWithGroup(String applyid) {
        try {
            return ResponseDTO.succData(this.apl_agentService.getAgentWithGroup(applyid));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "查询失败");
        }
    }

    /**
     * 申请人查询-全部查询
     */
    @Override
    public ResponseDTO getAgentByApplyid(String applyid) {
        try {
            List<Apl_agent> agentList = this.apl_agentService.getAgentByApplyid(applyid);
            if (CollectionUtil.isNotEmpty(agentList)) {
                for (Apl_agent apl_agent : agentList) {
                    apl_agent.geneText();
                }
            }
            return ResponseDTO.succData(agentList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "查询失败");
        }
    }

    @Override
    public ResponseDTO searchByName(String name) {
        try {
            List<Apl_agent> agentList = this.apl_agentService.searchByName(name);
            if (CollectionUtil.isNotEmpty(agentList)) {
                for (Apl_agent apl_agent : agentList) {
                    apl_agent.geneText();
                }
            }
            return ResponseDTO.succData(agentList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "查询失败");
        }
    }

    @Override
    public ResponseDTO updateAttachId(String id, Integer type, String attachId) {
        try {
            Assert.notNull(type, "操作类型不能为空");
            Apl_agent agent = this.apl_agentService.getById(id);
            switch (type) {
                case 0:
                    agent.setFilecard(attachId);
                    break;
                case 1:
                    agent.setDoccard(attachId);
                    break;
                case 2:
                    agent.setFileentrust(attachId);
                    break;
                default:
                    break;
            }
            this.apl_agentService.saveOrUpdate(agent);
            return ResponseDTO.succ();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "更新附件id失败");
        }
    }

    @Override
    public ResponseDTO deleteAttachId(String id, Integer type, String attachId) {
        try {
            Assert.notNull(type, "操作类型不能为空");
            Apl_agent apl_agent = this.apl_agentService.getById(id);
            // 删除文件
            FileController fileController = SpringHolder.getBean(FileController.class);
            fileController.minioRemove(null,attachId);
            switch (type) {
                case 0:
                    String filecardId = apl_agent.getFilecard();
                    if (!StringUtil.isEmpty(filecardId)) {
                        List<String> restFileIds = Arrays.asList(filecardId.split(",")).stream().filter(item -> !item.equals(attachId)).collect(Collectors.toList());
                        if (CollectionUtil.isEmpty(restFileIds)) {
                            apl_agent.setFilecard(null);
                        }
                        apl_agent.setFilecard(String.join(",", restFileIds));
                    }
                    break;
                case 1:
                    String doccardId = apl_agent.getDoccard();
                    if (!StringUtil.isEmpty(doccardId)) {
                        List<String> restDocIds = Arrays.asList(doccardId.split(",")).stream().filter(item -> !item.equals(attachId)).collect(Collectors.toList());
                        if (CollectionUtil.isEmpty(restDocIds)) {
                            apl_agent.setDoccard(null);
                        }
                        apl_agent.setDoccard(String.join(",", restDocIds));
                    }
                    break;
                case 2:
                    String fileentrustId = apl_agent.getFileentrust();
                    if (!StringUtil.isEmpty(fileentrustId)) {
                        List<String> thirdEvidenceIds = Arrays.asList(fileentrustId.split(",")).stream().filter(item -> !item.equals(attachId)).collect(Collectors.toList());
                        if (CollectionUtil.isEmpty(thirdEvidenceIds)) {
                            apl_agent.setFileentrust(null);
                        }
                        apl_agent.setFileentrust(String.join(",", thirdEvidenceIds));
                    }
                    break;
                default:
                    break;
            }
            this.apl_agentService.saveOrUpdate(apl_agent);
            return ResponseDTO.succ();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "删除附件失败");
        }
    }


}
